var express = require("express");
var router = express.Router();
const Db = require("../utils/db");
const createSql = require("../utils/Create_SQL");
const path = require('path');
const { errorCode, successCode, config } = require('../config/config');
const utils = require('../utils/utils.js');
const objectCheck = require("./commentApiCheck.js");

/**
 * @swagger
 * /api/comment/addComment:
 *    post:
 *      tags:
 *      - 评论相关
 *      summary: 添加评论
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                articleId:
 *                  type: string
 *                  description: 文章id
 *                  required: true
 *                content:
 *                  type: string
 *                  description: 评论内容
 *                  required: true
 *                replyId:
 *                  type: string
 *                  description: 回复id
 *                token:
 *                  type: string
 *                  description: token 非必填 微信小程序使用
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post('/addComment', async (req, res) => { 
    let isLogin = {};
    try {
        isLogin = await utils.isUserLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code != 200) return;
    let data = utils.checkData(req.body, objectCheck.comment_add , true);
    if (data.code > 200) return res.json(data);
    data = data.data;
    data.createByUser = isLogin.data.ID;
    data.addtime = utils.getTime();
    data.ID = utils.getUuid();
    data.replyId ? data.reply_id = data.replyId : null ;
    data.article_id = data.articleId;
    data.ip = utils.getClientIP(req);
    delete data.replyId;
    delete data.articleId;
    let sql = createSql.insert("article_comment").value(data).end();
    let reslut = await Db.query(sql , res);
    if(reslut.code > 200) return ;
    return res.json(successCode[200]);
});

/**
 * @swagger
 * /api/comment/getCommentByArticleId:
 *    get:
 *      tags:
 *      - 评论相关
 *      summary: 根据文章id获取评论
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: articleId
 *          description: 文章id
 *          in: query
 *          required: true
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get('/getCommentByArticleId', async (req, res) => {
    let articleId = req.query.articleId;
    if (!articleId) {
        res.status(500);
        return res.json({
            ...errorCode[10003]
        })
    }
    let pass = utils.detectSQL(articleId);
    if(!pass){
        res.status(500);
        return res.json(
            errorCode[10020]
        )
    }
    let sql = createSql.select().from("article_comment_view").where(`is_del != 1 AND article_id = '${articleId}' AND is_show != 0 `).order("addtime", "desc").end();
    let result = await Db.query(sql, res);
    let noReply = [], reply = [];
    result.forEach(v => {
        v.addtime = utils.formatDate(v.addtime);
        v.icon = v.icon ? global.ip + v.icon : global.ip + 'img/weixin.png';
        v.username = v.username ? v.username : "匿名用户";
        if (!v.reply_id || v.reply_id == "") {
            v.list = [];
            noReply.push(v);
            return;
        }
        reply.push(v);
    });

    noReply.forEach(v => {
        v.list = reply.filter(item => v.ID == item.reply_id);
        v.list.sort((a , b) =>(b.is_top - a.is_top) || (b.is_refining - a.is_refining))
    })
    noReply.sort((a , b) =>(b.is_top - a.is_top) || (b.is_refining - a.is_refining))
    res.json({
        ...successCode[200],
        data: noReply
    })
});

/**
 * @swagger
 * /api/comment/deleteComment:
 *    post:
 *      tags:
 *      - 评论相关
 *      summary: 删除评论
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 评论ID
 *                  required: true
 *                token:
 *                  type: string
 *                  description: token 非必填 微信小程序使用
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/deleteComment" , async (req , res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isUserLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code != 200) return;
    const {ID} = req.body;
    let pass = utils.detectSQL(ID);
    if(!pass){
        res.status(500);
        return res.json(
            $errorCode[10020]
        )
    }
    let sql = createSql.select().from("article_comment").where(`ID = '${ID}'`).and(`createByUser = '${isLogin.data.ID}'`).end();
    let result = await Db.query(sql , res);
    if(result.code > 200) return ;
    if(!result.length){
        return res.json({
            ...errorCode[10001],
            message : "当前用户没有这条评论"
        })
    }
    sql = createSql.update("article_comment").set({is_del : 1}).where(`ID = '${ID}'`).end();
    result = await Db.query(sql , res);
    if(result.code > 200) return ;
    return res.json(successCode[200]);
})

module.exports = router;